
Page({
  data: {
    phone: '',
    code: '',
    canSendCode: true,
    countdown: 0,
    agreementChecked: false
  },

  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    });
  },

  onAgreementChange(e) {
    console.log('协议勾选事件详情:', e.detail);
    // 更准确地处理 checkbox 状态
    // 当勾选时，e.detail.value 应该包含 ['agreement']，取消勾选时为空数组 []
    const isChecked = e.detail.value.includes('agreement');
    console.log('是否勾选:', isChecked, 'value:', e.detail.value);
    this.setData({
      agreementChecked: isChecked
    });
  },

  sendCode() {
    if (!this.data.phone) {
      wx.showToast({ title: '请输入手机号', icon: 'none' });
      return;
    }

    if (!this.data.canSendCode) return;

    // 发送验证码逻辑
    this.setData({
      canSendCode: false,
      countdown: 60
    });

    const timer = setInterval(() => {
      if (this.data.countdown <= 1) {
        clearInterval(timer);
        this.setData({
          canSendCode: true,
          countdown: 0
        });
      } else {
        this.setData({
          countdown: this.data.countdown - 1
        });
      }
    }, 1000);

    wx.showToast({ title: '验证码已发送', icon: 'success' });
  },

  login() {
    if (!this.data.agreementChecked) {
      wx.showToast({ title: '请勾选同意用户协议和隐私政策', icon: 'none' });
      return;
    }

    if (!this.data.phone) {
      wx.showToast({ title: '请输入手机号', icon: 'none' });
      return;
    }

    if (!this.data.code) {
      wx.showToast({ title: '请输入验证码', icon: 'none' });
      return;
    }

    console.log('开始登录，准备跳转到首页...');
    
    // 设置用户信息和token
    const app = getApp();
    const mockUser = {
      id: 'user_' + Date.now(),
      nickname: '用户' + this.data.phone.slice(-4),
      avatar_url: '', // 使用空字符串，前端可以显示默认头像
      age: Math.floor(Math.random() * 10) + 20,
      city: '北京',
      gender: 'male'
    };
    
    const mockToken = 'token_' + Date.now();
    
    // 保存到本地存储和全局数据
    wx.setStorageSync('token', mockToken);
    wx.setStorageSync('userInfo', mockUser);
    app.globalData.token = mockToken;
    app.globalData.userInfo = mockUser;
    
    console.log('用户信息已设置:', mockUser);
    
    // 登录逻辑
    wx.showToast({ 
      title: '登录成功', 
      icon: 'success',
      success: () => {
        console.log('登录成功提示显示完成，准备跳转');
        setTimeout(() => {
          try {
            console.log('执行 wx.switchTab 跳转');
            wx.switchTab({ 
              url: '/pages/index/index',
              success: (res) => {
                console.log('跳转成功:', res);
              },
              fail: (err) => {
                console.error('跳转失败:', err);
                wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
              }
            });
          } catch (error) {
            console.error('跳转异常:', error);
            wx.showToast({ title: '跳转异常，请重试', icon: 'none' });
          }
        }, 1500);
      }
    });
  },

  wechatLogin() {
    if (!this.data.agreementChecked) {
      wx.showToast({ title: '请勾选同意用户协议和隐私政策', icon: 'none' });
      return;
    }

    console.log('开始微信登录...');
    wx.login({
      success: async (res) => {
        if (res.code) {
          try {
            console.log('获取到微信登录 code:', res.code);
            
            // 设置用户信息和token
            const app = getApp();
            const mockUser = {
              id: 'wx_user_' + Date.now(),
              nickname: '微信用户',
              avatar_url: '', // 使用空字符串，前端可以显示默认头像
              age: Math.floor(Math.random() * 10) + 20,
              city: '北京',
              gender: 'male'
            };
            
            const mockToken = 'wx_token_' + Date.now();
            
            // 保存到本地存储和全局数据
            wx.setStorageSync('token', mockToken);
            wx.setStorageSync('userInfo', mockUser);
            app.globalData.token = mockToken;
            app.globalData.userInfo = mockUser;
            
            console.log('微信用户信息已设置:', mockUser);
            
            wx.showToast({ 
              title: '微信登录成功', 
              icon: 'success',
              success: () => {
                setTimeout(() => {
                  console.log('微信登录成功，准备跳转到首页');
                  wx.switchTab({ 
                    url: '/pages/index/index',
                    success: (res) => {
                      console.log('微信登录跳转成功:', res);
                    },
                    fail: (err) => {
                      console.error('微信登录跳转失败:', err);
                      wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
                    }
                  });
                }, 1500);
              }
            });
          } catch (error) {
            console.error('微信登录异常:', error);
            wx.showToast({ title: '登录失败', icon: 'error' });
          }
        } else {
          console.error('微信登录失败:', res);
          wx.showToast({ title: '微信登录失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('wx.login 调用失败:', err);
        wx.showToast({ title: '登录失败，请重试', icon: 'none' });
      }
    });
  },

  viewAgreement() {
    wx.showModal({
      title: '用户协议',
      content: '这里是用户协议内容',
      showCancel: false
    });
  },

  viewPrivacy() {
    wx.showModal({
      title: '隐私政策',
      content: '这里是隐私政策内容',
      showCancel: false
    });
  },
  
  async updateUserInfo(userInfo) {
    await wx.request({
      url: 'https://api.yourdomain.com/api/v1/users/me',
      method: 'PATCH',
      header: { Authorization: `Bearer ${wx.getStorageSync('token')}` },
      data: {
        nickname: userInfo.nickName,
        avatar_url: userInfo.avatarUrl,
        gender: userInfo.gender,
        city: userInfo.city
      }
    });
  }
});
